<template>
  <el-row :gutter="20" style="height: 100%">
    <el-col :span="12">
      <el-scrollbar style="height: 100%">
        <el-row style="padding: 0 25px">
          <el-collapse>
            <el-collapse-item title="STEP 1: 函数说明">
              <mavon-editor
                v-model="introText"
                :toolbars="mavonEditorToolbars"
                :subfield="false"
                placeholder="请输入对这个函数作用的如何使用的说明"
                style="width: 98%; margin: 0 auto;z-index: 1!important;"
                @imgAdd="addImg"
              />
            </el-collapse-item>
            <el-collapse-item title="STEP 2: 变量说明">
              <el-row v-for="variable in variables" :key="variable.name">
                <el-row :gutter="50" class="name-container">
                  <el-col :span="14">
                    <el-input
                      v-model="variable.name"
                      size="large"
                      readonly="true"
                    >
                      <template #prepend> 变量名 </template>
                    </el-input>
                  </el-col>
                  <el-col :span="10">
                    <el-input
                      v-model="variable.type"
                      size="large"
                    >
                      <template #prepend>类型</template>
                    </el-input>
                  </el-col>
                </el-row>
                <el-col :span="20">
                  <div class="intro-container" style="border:solid 1px #DCDFE6; border-radius:4px">
                    <div class="variable-intro">说明文字</div>
                    <div class="textarea-container">
                      <textarea v-model="variable.intro" name="variableIntro" rows="3" cols="80" style="resize:none;width:100%" />
                    </div>
                  </div>
                </el-col>
              </el-row>

            </el-collapse-item>
            <el-collapse-item title="STEP 3: 返回说明">
              <el-row>
                <el-button
                  type="primary"
                  size="mini"
                  @click="addReturnValue"
                >
                  添加
                </el-button>
              </el-row>
              <el-row v-for="(returnValue, index) in returnValues" :key="returnValue.index">
                <el-row :gutter="50" class="name-container">
                  <el-col :span="14">
                    <el-input
                      v-model="returnValue.name"
                      size="large"
                    >
                      <template #prepend> 变量名 </template>
                    </el-input>
                  </el-col>
                  <el-col :span="10">
                    <el-input
                      v-model="returnValue.type"
                      size="large"
                    >
                      <template #prepend>类型</template>
                    </el-input>
                  </el-col>
                </el-row>
                <el-row class="retintro-container">
                  <el-col :span="20">
                    <div class="intro-container" style="border:solid 1px #DCDFE6; border-radius:4px">
                      <div class="variable-intro">说明文字</div>
                      <div class="textarea-container">
                        <textarea v-model="returnValue.intro" name="returnValueIntro" rows="3" cols="80" style="resize:none;width:100%" />
                      </div>
                    </div>
                  </el-col>
                </el-row>
                <el-col :span="5">
                  <el-button
                    type="danger"
                    size="mini"
                    plain
                    @click="removeReturnValue(index)"
                  >
                    删除
                  </el-button>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
          <el-row />
          <el-row>
            <el-button
              type="primary"
              size="mini"
              @click="saveEvent"
            >
              保存修改
            </el-button>
          </el-row>
        </el-row>
      </el-scrollbar>
    </el-col>
    <el-col :span="12">
      <el-scrollbar style="height: 100%">
        <mavon-editor
          v-model="configMDFile"
          :subfield="false"
          :default-open="'preview'"
          :editable="false"
          :toolbars-flag="false"
          :scroll-style="true"
          style="width: 98%; margin: 0 auto;z-index: 1!important;"
        />
      </el-scrollbar>
    </el-col>
  </el-row>

</template>

<script>
import jsYaml from 'js-yaml';
import { mapActions, mapState } from 'vuex';
import { getObjectUrl } from '@/utils/aliOss';
import { downloadOss } from '@/api/userProject';
import { parseParameters } from '@/utils/util';

export default {
  name: 'ConfigTab',
  data() {
    return {
      introText: '',
      functionPrototype: '',
      variables: [],
      returnValues: [],

      mavonEditorToolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: false, // code
        table: false, // 表格
        fullscreen: false, // 全屏编辑
        readmodel: false, // 沉浸式阅读
        htmlcode: false, // 展示html源码
        help: true, // 帮助
        undo: false, // 上一步
        redo: false, // 下一步
        trash: false, // 清空
        save: false, // 保存（触发events中的save事件）
        navigation: false, // 导航目录
        alignleft: false, // 左对齐
        aligncenter: false, // 居中
        alignright: false, // 右对齐
        subfield: false, // 单双栏模式
        preview: false // 预览
      }
    };
  },
  computed: {
    ...mapState('functions', ['templateFiles', 'isUploadTemplateFile', 'serviceName', 'functionName']),
    configFile() {
      return this.templateFiles.config;
    },
    configMDFile() {
      const functionNameSection = `# ${this.functionName}`;
      const prototypeSection = `### pangu.${this.serviceName.substring(66)}.${this.functionName}(*${this.functionPrototype}*)`;
      const functionIntroSection = this.introText;
      const varibales = this.variables;
      const returns = this.returnValues;
      /*
      const varibales = [{
        name: 'a',
        type: '(N,) array_like',
        intro: '这是一个数组，作为inf的第一个参数'
      }];
      const returns = [{
        name: 'x',
        type: '(N,) array_like',
        intro: '这是一个数组，作为inf的第一个返回值'
      }];
      */
      var varbArray = varibales.map((data) => {
        var varTypeStr = data.type;
        if (varTypeStr !== '') {
          varTypeStr = `: *${data.type}*`;
        }
        var totalStr = `${data.name}` + varTypeStr;
        return `&emsp;**${totalStr}**\n &emsp;${data.intro}\n`;
      });
      var varbStr = '';
      for (var i = 0; i < varbArray.length; i++) {
        varbStr += varbArray[i];
      }
      var parametersSection = '### Parameters:\n' + varbStr;
      var returnArray = returns.map((data) => {
        var retNameStr = data.name;
        var retTypeStr = data.type;
        if (retNameStr !== '') {
          retNameStr = `${data.name}`;
        } else {
          retNameStr = '';
        }
        if (retTypeStr !== '') {
          retTypeStr = `: *${data.type}*`;
        }
        var totalStr;
        if (retNameStr === '' && retTypeStr === '') {
          totalStr = '';
        } else {
          totalStr = `&emsp;**${retNameStr}${retTypeStr}**`;
        }
        return `${totalStr}\n &emsp;${data.intro}\n`;
      });
      var returnStr = '';
      for (var j = 0; j < returnArray.length; j++) {
        returnStr += returnArray[j];
      }
      var returnsSection = '### Returns:\n' + returnStr;
      return `${functionNameSection}\n${prototypeSection}\n${functionIntroSection}\n${parametersSection}\n${returnsSection}`;
    }
  },
  mounted() {
    document.addEventListener('keydown', this.keyBoardSave);
    this.initParams();
  },
  destroyed() {
    document.removeEventListener('keydown', this.keyBoardSave);
  },

  methods: {
    ...mapActions('functions', ['buildTemplateFile']),
    keyBoardSave(e) {
      // js监听键盘ctrl+s快捷键保存
      if (
        e.keyCode === 83 &&
        (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)
      ) {
        e.preventDefault();
        // 检查函数编辑区是否有改变
        const store = this.$store.state.functions;
        const isNotEdited = store.editorFiles.every(
          (item) => item.editText === store.editContent
        );
        if (!isNotEdited) {
          this.initParams();
        }
        this.saveEvent();
      }
    },
    saveEvent() {
      this.configFile.editContent = this.convertToYaml(); // 转换成Yaml文件
      // console.log(this.configFile.editContent);
      if (this.isUploadTemplateFile[this.configFile.id]) {
        this.$message.error('文件正在保存中...');
        return;
      }
      if (this.configFile.editText !== this.configFile.editContent) { // 新老内容不同
        this.buildTemplateFile(this.configFile);
      }
    },
    async initParams() { // 读取用户的参数列表进行初始化
      const that = this;
      const name = `userLibrary/${this.serviceName}/${this.functionName}/${this.functionName}.py`;
      const url = await getObjectUrl(name);
      const resp = await downloadOss(url);
      const func = this.functionName;
      resp.text().then(function(content) {
        var funcInfo = parseParameters(func, content);
        that.functionPrototype = funcInfo['functionPrototype'];
        that.introText = funcInfo['introText'];
        that.variables = funcInfo['variables'];
        if (that.returnValues.length <= 1) {
          that.returnValues.push({
            name: 'example',
            type: 'int',
            intro: '这是...(变量类型), 表示...的含义, 用于..., 默认值是...'
          });
        }
      });
      await this.loadFromYaml();
    },
    convertToYaml() {
      return jsYaml.dump({
        'prototype': `pangu.${this.serviceName.substring(66)}.${this.functionName}` + `(${this.functionPrototype})`,
        'variables': this.variables,
        'intro': this.introText,
        'returns': this.returnValues
      });
    },

    async loadFromYaml() {
      // TODO: 通过config.yaml文件的内容，初始化几个不同位置的数据，打开本tab时自动调用
      const that = this;
      const path = `userTemplates/${this.serviceName}/${this.functionName}/config.yaml`;
      const url = await getObjectUrl(path);
      const resp = await downloadOss(url);

      resp.text().then(function(content) {
        const ossContent = content;
        const data = jsYaml.load(ossContent);

        const initVariables = JSON.parse(JSON.stringify(that.variables));
        const savedVariables = JSON.parse(JSON.stringify(data.variables));
        that.variables = [];
        for (var i = 0; i < initVariables.length; i++) {
          var found = -1;
          for (var j = 0; j < savedVariables.length; j++) {
            if (savedVariables[j].name === initVariables[i].name) {
              found = j;
            }
          }
          if (found === -1) {
            that.variables.push(initVariables[i]);
          } else {
            that.variables.push(savedVariables[found]);
          }
        }

        that.introText = data.intro;
        that.returnValues = data.returns.map((item) => {
          return {
            name: item.name,
            type: item.type,
            intro: item.intro
          };
        });
      });
    },
    addReturnValue() {
      this.returnValues.push({
        name: '',
        type: '',
        intro: ''
      });
    },
    removeReturnValue(index) {
      this.returnValues.splice(index, 1);
    },
    addImg(pos, file) {
      const imgData = new FormData();
      imgData.append('file', file);
      this.$axios.post('/files/image/upload', imgData).then(res => {
        this.$refs.md.$img2Url(pos, res.data.data);
      });
    }
  }
};

</script>

<style lang="scss">
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
  height: 100%;
}
.name-container{
    margin-bottom: 10px;
    margin-left:50px;
    width:90%;
  }
  .retintro-container{
    margin-bottom: 10px;
  }
  .intro-container{
    background-color: #F5F7FA;
    .variable-intro{
    padding:5px 20px;
    font-size: 14px;
    color:#909399;
    }
    .textarea-container{
      padding: 0 20px;
    }
  }

.el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
